# -*- coding: utf-8 -*-

from fire_control_spider.utils import ContentProcessor
from bs4 import BeautifulSoup
from ..base_parser import BasePageParser
from .common import extract_menu_info, update_media_urls

class IncidentDetailParser(BasePageParser):
    """新闻详情页解析器"""
    
    def __init__(self, spider):
        super().__init__(spider)
        self.site_name = 'londonfire_gov_uk'
        
    
    def can_handle(self, response):
        """判断是否为新闻详情页"""
        return response.meta.get('page_type') == 'incident_detail'
    
    def parse(self, response):
        """解析新闻详情页"""
        self.logger.info(f"开始处理详情页 {response.url}")
        
        # 创建基础item
        item = self.create_webpage_item(response)
        
        # 使用BeautifulSoup提取标题
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 提取菜单信息
        item['category'] = extract_menu_info(soup)
        
        title = ''
        # 尝试多种标题选择器
        title_selectors = ['.article-header__title']
        for selector in title_selectors:
            title_element = soup.select_one(selector)
            if title_element:
                title = title_element.get_text(strip=True)
                break
        
        if title:
            item['title'] = title
        
        pub_date = soup.select_one('.article-header__date').get_text(strip=True)
        pub_time = soup.select_one('.article-header__time').get_text(strip=True)

        pub_datetime = f"{pub_date} {pub_time}"
        # 将'29/07/2025 19:54' 转换为 '2025-07-29 19:54'
        from datetime import datetime
        try:
            dt = datetime.strptime(pub_datetime, "%d/%m/%Y %H:%M")
            item['publish_time'] = dt.strftime("%Y-%m-%d %H:%M")
        except Exception as e:
            self.logger.warning(f"发布日期格式转换失败: {pub_datetime}，错误: {e}")
            item['publish_time'] = pub_datetime
        
        # 提取正文内容并处理图文交错
        main_content = self._extract_main_content(soup)
        if main_content:
            main_body, media_urls = ContentProcessor.process_content_with_media(
                main_content, response.url, self.site_name
            )
            item['main_body'] = main_body

            # 更新媒体URLs
            update_media_urls(item, media_urls)

        
        # 添加新闻特有信息
        item['remark'] = {
            "loc": soup.select_one('.article-header__loc').get_text(strip=True),
            "fire_type": soup.select_one('.article-header__type').get_text(strip=True),
        }
        
        yield item
    
    def _extract_main_content(self, soup):
        
        # 主要选择器
        selector = 'main.page'
        content_element = soup.select_one(selector)
        if content_element:
            return str(content_element)
    
        return ''
    
